#include <stdio.h>
#include "pico/stdlib.h"
#include "pico/binary_info.h"
#include "hardware/spi.h"

#include "wizchip_conf.h"
#include "bsp_spi.h"
#include "socket.h"
#include "sntp.h"
#include "dhcp.h"

#define SOCKET_ID 0
#define ETHERNET_BUF_MAX_SIZE (1024 * 2)
#define DHCP_RETRY_COUNT 5 // DHCP retry times

wiz_NetInfo net_info = {
    .mac = {0x00, 0x08, 0xdc, 0x16, 0xed, 0x2e}, // Define MAC variables
    .ip = {192, 168, 1, 10},                     // Define IP variables
    .sn = {255, 255, 255, 0},                    // Define subnet variables
    .gw = {192, 168, 1, 1},                      // Define gateway variables
    .dns = {8, 8, 8, 8},                         // Define DNS  variables
    .dhcp = NETINFO_DHCP};                       // Define the DNCP mode
wiz_NetInfo get_info;
static uint8_t ethernet_buf[ETHERNET_BUF_MAX_SIZE] = {
    0,
};
static uint8_t sntp_server_ip[4] = {202, 112, 10, 60};
static uint16_t timezone = 39;
static uint8_t sntp_get_ip_count = 0;
datetime date;
static uint8_t dhcp_get_ip_flag = 0; // Define the DHCP acquisition flag

/**
 * @brief   Timer callback processing function, used for dhcp timing processing
 * @param   repeating :Timer structure
 * @return  bool
 */
bool repeating_timer_callback(struct repeating_timer *t);

/**
 * @brief   Initialization of chip network information
 * @param   conf_info :Static configuration information
 * @return  none
 */
void network_init(wiz_NetInfo *conf_info);

int main()
{
    struct repeating_timer timer; // Define the timer structure

    /*mcu init*/
    stdio_init_all();              // Initialize the main control peripheral
    wizchip_initialize();          // spi initialization
    wizchip_setnetinfo(&net_info); // Configure once first

    /*dhcp init*/
    DHCP_init(SOCKET_ID, ethernet_buf);                                   // DHCP initialization
    add_repeating_timer_ms(1000, repeating_timer_callback, NULL, &timer); // Add DHCP 1s Tick Timer handler

    network_init(&net_info);              // Configuring Network Information
    print_network_information(&get_info); // Read back the configuration information and print it

    /*sntp init*/
    SNTP_init(SOCKET_ID, sntp_server_ip, timezone, ethernet_buf); // NTP protocol initialization parameters
    printf("wiznet chip sntp client example.\r\n");

    while (true)
    {
        sntp_get_ip_count++;
        sleep_ms(1000);  // Print once a second
        SNTP_run(&date); // The NTP protocol obtains the current time from the server at the time of authorization
        if (sntp_get_ip_count > 2)
        {
            printf("NOW: %d-%d-%d  %d:%d:%d\r\n", date.yy, date.mo, date.dd, date.hh, date.mm, date.ss);
        }
    }
}

bool repeating_timer_callback(struct repeating_timer *t)
{
    DHCP_time_handler(); // DHCP 1s Tick Timer handler
    return true;
}

void network_init(wiz_NetInfo *conf_info)
{
    int count = 0;
    int dhcp_state = 0;
    int breakout_flag = 0;

    if (conf_info->dhcp == NETINFO_DHCP)
    {
        while (true)
        {
            dhcp_state = DHCP_run(); // Do the DHCP client

            switch (dhcp_state)
            {
            case DHCP_IP_LEASED: // DHCP obtained the IP successfully
                if (dhcp_get_ip_flag == 0)
                {
                    dhcp_get_ip_flag = 1;
                    breakout_flag = 1;
                    getSHAR(get_info.mac);
                    getIPfromDHCP(get_info.ip);
                    getGWfromDHCP(get_info.gw);
                    getSNfromDHCP(get_info.sn);
                    getDNSfromDHCP(get_info.dns);
                    get_info.dhcp = NETINFO_DHCP;

                    /* Network initialize */
                    network_initialize(get_info); // apply from DHCP

                    printf(" DHCP leased time : %ld seconds\n", getDHCPLeasetime());
                }
                break;
            case DHCP_FAILED: // DHCP failed to obtain IP
                count++;
                if (count <= DHCP_RETRY_COUNT) // If the number of times is less than or equal to the maximum number of times, try again
                {
                    printf(" DHCP timeout occurred and retry %d \r\n", count);
                }
                else if (count > DHCP_RETRY_COUNT) // If the number of times is greater than DHCP fails
                {
                    breakout_flag = 1;
                    printf(" DHCP failed \r\n");
                    DHCP_stop(); // Stop processing DHCP protocol

                    net_info.dhcp = NETINFO_STATIC;
                    wizchip_setnetinfo(&net_info); // Write configuration information
                }
            }
            if (breakout_flag == 1) // Get out of the loop
            {
                printf("config succ\r\n");
                break;
            }
        }
    }
    else
    {
        wizchip_setnetinfo(&net_info); // Configuring Network Information
    }
}
